define(function(require, exports){
	var $		= require("jquery");
	var pubjs	= require('pubjs');
	var view	= require('@base/view');
	var util	= require('util');
	var currencyList = pubjs.config("currency"); //获取汇率表
	var All = currencyList['all'];
	var List = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				"class": 'P-financeDetail',
				// 当前货币
				"currency":"rmb",
				"infoUrl":"cost/multiCurrency",
				'vModel':{
					'info':[
						{
							currencyTypeId:'-', //货币类型id
							currencyTypeName:'-', //货币名称
							Remain: '-',
							AllowAdCredit:'-', //信用额度
							availableCreditTmp:'-', //可用额度
							gather:'-',   //历史汇总
							TodayCost:'-'
						}
					],
				},
			});

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			var c = self.getConfig();

			self.append($([
				'<div class="M-formHead">',
					// '<label class="M-formHeadTitle">'+LANG('财务中心')+'</label>',
					'<div class="P-financeDetailHeader w600 mb10 dib">',
						'<div class="mt10">',
							'<span class="account"><label>'+LANG("账户余额：")+'</label></span>',
							'<table class="table table-bordered mt20 mb20" >'+
								'<thead style="border:0;">'+
									'<tr>'+
										'<th class="w25pct tl">'+LANG('货币类型')+'</th>'+
										'<th class="w25pct tl">'+LANG('账户余额')+'</th>'+
										'<th class="w25pct tl">'+LANG('信用额度')+'</th>'+
										'<th class="w25pct tl">'+LANG('可用额度')+'</th>'+
										'<th class="w25pct tl">'+LANG('历史汇总')+'</th>'+
									'</tr>'+
								'</thead>'+
								'<tbody style="border:1px solid #cccccc">'+
									'<tr v-for="item in info">'+
										'<td class="w20pct tl"> {{item.currencyTypeName}}</td>'+
										'<td class="w20pct tl"> {{item.Remain}}</td>'+
										'<td class="w20pct tl"> {{item.AllowAdCredit}}</td>'+
										'<td class="w20pct tl"> {{item.availableCreditTmp}}</td>'+
										'<td class="w20pct tl"> {{item.gather}}</td>'+
									'</tr>'+
								'</tbody>'+
							'</table>',
						'</div>',

						'<div class="P-financeHeaderClear"/>',
					'</div>',
				'</div>',
				'<div class="P-financeDetailHeader mb20 dib">',
					'<span class="account"><label>'+LANG("财务记录：")+'</label></span>',
				'</div>',
				'<span class="fr " pub-name="date" pub-mod="@base/common/date.dateRangeNew"/>',

				'<div class="cl" pub-name="highGrid" pub-mod="admin/financeCenter/grid/financeDetail.base"/>',
			].join('')));

			var config = {
				highGrid: {
					'hasSearch': true,
					'hasRefresh': true,
					'userStorageDate': false,
					'auto_load': true
				},
				date:{
					'pos': 'bR',
					'userStorage': false,
					'broadcast': false,
					'hasNoLimit': true
				}
			};
			self.buildFromTemplate(config);
			this.vm.mount();
			var type = pubjs.getUser().current.Type;
			var isCredit = pubjs.getUser().current.IsCredit;
			// 仅可充保证金客户,才有'保证金'选项
			// 仅代理客户，才有'返点'和'收益'选项
			var typeRadioData =[
				{id: 0, name: LANG('所有')},
				{id: 1, name: LANG('预充值')},
				(isCredit && {id: 2, name: LANG('保证金')}|| null),
				{id: 3, name: LANG('返款')},
				(type!=2 && {id: 4, name: LANG('返点')}|| null),
				{id: 5, name: LANG('扣费')},
				(type!=2 && {id: 6, name: LANG('收益')}|| null)
			];

			// 去掉无效项null
			var tmp = [];
			typeRadioData.forEach(function(data){
				if(data){
					tmp.push(data);
				}
			});
			typeRadioData = tmp;

			self.createAsync('sidebar', '@layout/v1/sidebar.base', {
				'target': c.targetSidebar,
				'height': 200,
				'attr': {'data-tab': self._.name},
				'items': [
					{'name': 'type', 'uri':'modules/sideBarBase.radio','config':{
						'title': LANG('类型：'),
						'data': typeRadioData,
						'value': 0
					}},
					{'name': 'source', 'uri':'modules/sideBarBase.radio','config':{
						'title': LANG('版本：'),
						'data': [
							{id: 0, name: LANG('所有')}
							,{id: 2, name: LANG('RTB广告')}
							//,{id: 6, name: LANG('PMP订单')}
							,{id: 5, name: LANG('直投广告')}
							,{id: 1, name: LANG('人工')}
						],
						'value': 0
					}}	// 状态
				]
			}, function() {
				self.get('sidebar/source').hide()
			});
		},
		/**
		 * 加载数据
		 * @param  {Number} id 账户id
		 * @return {Object}    模块实例
		 */
		load:function(){
			var self = this;
			var user = pubjs.getUser();
			if(!user.current.isAdmin){
				pubjs.mc.send(self.getConfig('infoUrl'),{},function(err, data){
					if(err){
						pubjs.log(err.message);
					}
					self.setData(data);
				});
			}
			return this;
		},
		onSidebarFilterGroup: function(ev){
			var self = this;
			var id = ev.param.id;
			switch (ev.name){
				case 'type':
					if(self.get('sidebar/source')){
						var hasSub = +id === 5;
						self.get('sidebar/source')[hasSub ? 'show' : 'hide']();
						if(hasSub){
							self.get('sidebar/source').setValue(0);
						}
					}

					break;
			}
			return false;
		},
		// 侧边栏响应事件
		onSidebarFilter: function(ev){
			var self = this
				,param = {};

			util.each(ev.param, function(item, idx){
				var type = idx;
				var id = item.id;

				switch (type) {
					case 'type':
						param.Type = +id;
						// 更新"金额汇总"标题
						self.updateSumTitle(+id);
						var hasSub = +id === 5;
						if(!hasSub) {
							param.Source = 0;
						}
						break;
					case 'source':
						param.Source = +id;
						break;
				}
			});

			self.$.highGrid.reload(param);
		},
		onDateRangeChange: function(ev){
			if(!this.getDOM().is(':visible')){
				return false;
			}
			// 设置日期参数
			var param = ev.param.nowTimestamp;
			this.reload(param);

			return false;
		},
		reload: function(param){
			this.load();
			this.$.highGrid.reload(param);
			return this;
		},
		/**
		 * 获取模块数据
		 * @return {Object}  模块数据
		 */
		setData:function(data){
			var data = util.clone(data);
			if(!data){
				return;
			}
			var def = data.def;
			var cost = data.currency;
			if(!cost && !def){
				return false;
			}
			if(!Array.isArray(cost) && !cost.length){
				return false;
			}
			var self = this;

			//可用额度
			var availableCreditTmp		= 0;
			var info					= pubjs.getUser(),
				finance					= info.current.Finance;
			if ( finance && finance.Credit && finance.Credit.AllowAdCredit > 0 ) {
				availableCreditTmp = finance.Credit.AllowAdCredit + (def.Rest < 0 ? def.Rest : 0);
				availableCreditTmp = availableCreditTmp < 0 ? 0 : availableCreditTmp;
			}
			//暂时只有默认货币有信用额度和可用额度
			def.AllowAdCredit = self.formatRest(finance.Credit.AllowAdCredit);
			def.availableCreditTmp = self.formatRest(availableCreditTmp);
			def.gather = self.formatRest(def.Amount);
			def.Remain = self.formatRest(def.Rest);
			if(def.Id){
				def.currencyTypeName = self.getCurrencyName(def.Id);
			}
			util.each(cost,function (item,ids) {
				//过滤余额
				item.Remain = self.formatRest(item.Rest);
				item.currencyTypeName = self.getCurrencyName(item.Id)
				item.AllowAdCredit = '-';
				item.availableCreditTmp = '-';
				item.gather = self.formatRest(item.Amount);
			});
			cost.unshift(def);
			//各种类型的余额（需要格式化），信用，可用（这个可能要过滤），类型（匹配）
			this.vm.$.info = cost;
			return this;
		},
		/**
		 * 格式化余额
		 * @param  {Number} val 余额
		 * @return {String}     格式化后的余额
		 */
		formatRest:function(val){
			val = util.round0(val,2);
			val = util.numberFormat(val);
			return val;
		},
		// 更新"金额汇总"标题
		updateSumTitle: function(id){
			var el = this.find('.sum'),
				type = el.find('p');

			var map = {
				0: LANG('所有'),
				1: LANG('预充值'),
				2: LANG('保证金'),
				3: LANG('返款'),
				4: LANG('返点'),
				5: LANG('扣费'),
				6: LANG('收益')
			};
			type.text(map[id]);
		},
		// 报表数据加载成功事件
		onGridDataLoad: function(ev){
			// 设置汇总数据
			var sum = this.find('.sum strong');
			sum.text(
				this.formatRest(ev.param.charge_sum)
			);
		},
		// 处理货币类型
		getCurrencyName: function (id) {
			var name;
			util.each(All,function(item){
				if(+id === +item.id){
					name = item.name;
				}
			});
			return name;
		}

	});

	exports.main = List;

});